package com.coolwen.controller;

import com.alibaba.fastjson.JSON;
import com.coolwen.entity.*;
import com.coolwen.service.CategoryService;
import com.coolwen.service.ProductService;
import com.coolwen.util.DateUtil;
import com.coolwen.util.PicUploadUtil;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by user on 2016/7/14.
 */
@Controller
@RequestMapping("/user/product/")
public class ProductController {

    private Logger logger = Logger.getLogger(getClass());
    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;

    @RequestMapping("list")
    public String list(Model model) {
        logger.info("product添加Post:" + JSON.toJSON(productService.find(0, null, 0)));
        model.addAttribute("products", productService.find(0, null, 0));
        return "product/list";
    }

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public String add(Model model) {
        List<Category> categories = categoryService.list("");
        model.addAttribute("product", new Product());
        model.addAttribute("cs", categories);
        logger.info("product添加Post:" + JSON.toJSON(categories));
        return "product/add";
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    public String add(@Validated Product product, BindingResult br, @RequestParam("attachs") MultipartFile[] attachs, HttpServletRequest req) {
        if (br.hasErrors()) {
            //如果有错误直接跳转到add视图

            return "product/add";
        }
        String realpath = req.getSession().getServletContext().getRealPath("/resources/upload");
//        logger.info("product添加realPath:" + JSON.toJSON(attachs));
        for (MultipartFile attach : attachs) {
            if (attach.isEmpty()) {
                continue;
            }
//            String pic_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
//            PicUploadUtil.formatDate(new Date());
            String picName = PicUploadUtil.picRename(attach.getContentType());
            String path = realpath + "/" + picName;
            File f = new File(path);
//            logger.info("product添加realpath:" + JSON.toJSON(realpath));
//            logger.info("product添加getOriginalFilename:" + JSON.toJSON(attach.getOriginalFilename()));
//            logger.info("product添加path:" + JSON.toJSON(path));
            product.setImg(picName);
            try {
                FileUtils.copyInputStreamToFile(attach.getInputStream(), f);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        logger.info("product添加Post:" + JSON.toJSON(product));
        product.setStatus(1);
        productService.add(product.getcId(), product);

        return "redirect:/user/product/list";
    }

    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    public String delete(@PathVariable int id) {
        productService.delete(id);
        return "redirect:/user/product/list";
    }

    @RequestMapping(value = "/{id}/show", method = RequestMethod.GET)
    public String show(@PathVariable int id, Model model) {
        model.addAttribute("product", productService.load(id));
        return "product/show";
    }

    @RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
    public String update(@PathVariable int id, Model model) {
        model.addAttribute(productService.load(id));
        List<Category> categories = categoryService.list("");
        model.addAttribute("cs", categories);
        return "product/update";
    }

    @RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
    public String update(@RequestParam("attachs") MultipartFile[] attachs, @PathVariable int id, @Validated Product p, BindingResult br, HttpServletRequest req) {
        if (br.hasErrors()) {
            return "product/update";
        }
        if (p.getcId() == 0)
            throw new ShopException("商品类别必须选择!");
        logger.info("product修改后p:" + JSON.toJSON(p));
        Product pd = productService.load(id);
        pd.setName(p.getName());
        pd.setPrice(p.getPrice());
        pd.setWeight(p.getWeight());
        pd.setStock(p.getStock());
        pd.setcId(p.getcId());
        pd.setIntro(p.getIntro());
        for (MultipartFile attach : attachs) {
            if (attach.isEmpty()) {
                continue;
            }
//            String realpath = req.getSession().getServletContext().getRealPath("/resources/upload");
            String path = SystemContext.getRealpath() + "/resources/upload/";
            System.out.println("删除图片的路径:" + path + pd.getImg());
            File f = new File(path + pd.getImg());
            f.delete();
            String picName = PicUploadUtil.picRename(attach.getContentType());
            String newPath = path + "/" + picName;
            f = new File(newPath);
            logger.info("productl类型realpath:" + JSON.toJSON(attach.getContentType()));
            //           logger.info("product添加getOriginalFilename:" + JSON.toJSON(attach.getOriginalFilename()));
//                pd.setImg(attach.getOriginalFilename());
            try {
                FileUtils.copyInputStreamToFile(attach.getInputStream(), f);
                pd.setImg(picName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        logger.info("product修改后pd:" + JSON.toJSON(pd));
        productService.update(pd.getcId(), pd);
        return "redirect:/user/product/list";
    }

    @RequestMapping(value = "{id}/add", method = RequestMethod.GET)
    public String addStock(@PathVariable int id) {
        return "redirect:/admin/product/list";
    }

    @RequestMapping("{id}/updateStatus")
    public String updateStatus(@PathVariable int id) {

        //只更商品状态
        Product p = productService.load(id);
        logger.info("product修改前p:" + JSON.toJSON(p));
        if (p.getStatus() == 1) {
            p.setStatus(-1);
        } else {
            p.setStatus(1);
        }
        logger.info("product修改后p:" + JSON.toJSON(p.getcId()));
        productService.update(p.getCategory().getId(), p);
        return "redirect:/user/product/list";
    }
}
